package top.melody.ecommerce.webapps.www.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
import top.melody.ecommerce.common.util.HTTPUtil;
import top.melody.ecommerce.common.util.JsonMapper;
import top.melody.ecommerce.platform.handler.enums.ResultMsg;
import top.melody.ecommerce.webapps.www.base.AssertContext;
import top.melody.ecommerce.webapps.www.base.UserSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SigninInterceptor implements HandlerInterceptor{

    private static final Logger logger = LoggerFactory.getLogger(AccountProfileInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //不拦截静态资源
        if (handler instanceof DefaultServletHttpRequestHandler)
            return true;
        try {
            //1.从session中获取,
            //2.如果没有,从Cookie中获取，
            //3.cookie中没有，则没有
            UserSession currentUser = AssertContext.getCurrentAccount(request);
            if(currentUser == null) {
                if(HTTPUtil.isJsonRequest(request)) {
                    //ajax请求，如果session过期，手动在页面上跳到登录页面
                    ResultMsg resultMsg = new ResultMsg(ResultMsg.CODE_NOT_LOGIN, "account login expired");
                    HTTPUtil.writeJson(response, JsonMapper.nonEmptyMapper().toJson(resultMsg));
                } else
                    response.sendRedirect(AssertContext.getContextPath(request) + "/account/sign/in");
                return false;
            }
        } catch (Exception e) {
            logger.error("occurred exception when encoding cookie key and value", e);
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}
